package com.xzy.sms.core.utils;

import java.util.HashMap;

import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;

/**
 * @desc ehcache 缓存工具类(cacheName在ehcache.xml中配置)
 * @author wjw
 * @time 2017年11月16日上午11:03:05
 */
public class EhcacheUtil {

	public static CacheManager manager = CacheManager.create();
	
	public final static String eternalCache ="smsEternalCache";//缓存块name
	
	/**
	 * 获取缓存name块中key指定缓存
	 * @param cacheName
	 * @param key
	 * @return Element
	 */
	public static Object get(String cacheName, Object key) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			Element element = cache.get(key);
			if (element != null) {
				return element.getObjectValue();
			}
		}
		return null;
	}
	
	/**
	 * 获取缓存对象map中指定的key值
	 * @param key
	 * @param mapKey
	 * @param mapValue
	 * @return Object
	 */
	public static Object getObj(String cacheName, Object key, String mapKey) {
		
		HashMap<String, Object> map = (HashMap<String, Object>) get(cacheName,key);;
		if ( map ==null) {
			map = new HashMap<String, Object>();
		}
		Object val = map.get(mapKey);
		return val;
	}
	
	/**
	 * 向指定缓存块中添加添加缓存对象(Element)
	 * @param cacheName
	 * @param key
	 * @param value
	 */
	public static void put(String cacheName, Object key, Object value) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			cache.put(new Element(key, value));
		}
	}
	
	/**
	 * 向指定缓存块且指定缓存对象map中添加元素
	 * @param key
	 * @param mapKey
	 * @param mapValue
	 */
	public static void put(String cacheName, Object key, String mapKey, Object mapValue) {
		
		HashMap<String, Object> map = (HashMap<String, Object>) get(cacheName,key);
		if ( map ==null ) {
			map = new HashMap<String, Object>();
		}
		map.put(mapKey, mapValue);
		put(cacheName, key, map);
	}
	
	/**
	 * 刪除缓存块中指定缓存对象key
	 * @param cacheName
	 * @param key
	 * @return
	 */
	public static boolean remove(String cacheName, Object key) {
		Cache cache = manager.getCache(cacheName);
		if (cache != null) {
			return cache.remove(key);
		}
		return false;
	}
	
	/**
	 * 刪除缓存块中缓存对象map中的元素
	 * @param cacheName
	 * @param key
	 * @param mapKey
	 * @return
	 */
	public static boolean remove(String cacheName, Object key, String mapKey) {
		HashMap<String, Object> map = (HashMap<String, Object>) get(cacheName,key);
		if ( map !=null ) {
			map.remove(mapKey);
			put(cacheName, key, map);
			return true;
		}
		return false;
	}

	public static void main(String[] args) {
		String key = "key";
		String value = "hello";
		EhcacheUtil.put("mytest", key, value);
		System.out.println(EhcacheUtil.get("mytest", key));
	}

}